var common = require("../../svr/libs/common")
var kms = require("../../svr/libs/kms")
var fs    = require('fs');
var path    = require('path');
var kmsConfig={    
    db:{
        dbKey:"kmsManageV201001",
        dbInfo:{
            host:"tjiot.hhdata.cn" ,
            port:53306,
            uid:"root",
            pwd:"hhuc1115",
            //db:"kms202101" ,
            sqlPath:"E:/app/kmsdev/dev/svr/sqls"
        }
    },
    kms:{
        kmsUrl : "wss://wss.hhdata.cn:8433/kurento"
    }
}

class TChannels{
    constructor(){
        this.url = "https://vkceyugu.cdn.bspapp.com/VKCEYUGU-learning-vue/52e72470-aecd-11ea-b997-9918a5dda011.mp4";
        this.kms = new kms.TKms(); 
        this.objs ={
            client: null ,
            pipe : null,
            playerEnd: null ,
            rtpEnd: null
        }
    }
    load(){
        var me = this;
        try{
            var onLoad = function(){
                console.log('load objs...');
                console.log(me.objs.pipe.id);
                console.log(me.objs.playerEnd.id);
                console.log(me.objs.rtpEnd.id);
                me.openRtp();
            }            
            me.kms.getClient( function(client){
                me.objs.client = client;
                me.kms.getKmsObj("MediaPipeline", null , "" , "rtp" , "rtpChannel" , "test" , "rtpPipe" , "" , function(pipe){
                    console.log('create pipe');
                    me.objs.pipe = pipe;
                    me.kms.getKmsObj("PlayerEndpoint", pipe , me.url , "rtp" , "rtpChannel" , "test" , "rtpPlayerEnd" , "" , function(playerEnd){
                        console.log('create player');
                        me.objs.playerEnd = playerEnd;
                        playerEnd.on("EndOfStream", function(){
                            playerEnd.play();
                        })
                        playerEnd.play( function(erPlayer){
                            me.kms.getKmsObj("RtpEndpoint", pipe , "" , "rtp" , "rtpChannel" , "test" , "rtpRtpEnd" , "" , function(rtpEnd){
                                console.log('create rptend');
                                me.objs.rtpEnd = rtpEnd;
                                playerEnd.connect(rtpEnd, function(erConnect){
                                    if( erConnect){
                                        console.log(erConnect);
                                    }
                                    else{
                                        console.log('connect player-->rtp.')
                                    }
                                    onLoad();
                                })
                            })
                        })
                    })
                })
            })
        }
        catch(er){
            console.log(er)
        }
    }  
    openRtp(){
        var me = this;
        var streamIp = '127.0.0.1';
        var streamPort = 49172;
        var audioport = 55002;
        me.generateSdpStreamConfig(streamIp , streamPort , audioport , function(err, sdpRtpOfferString){
            if( err){
                console.log(err); 
            }
            me.objs.rtpEnd.processOffer(sdpRtpOfferString, function (error) {
                if( error){
                    console.log(error); 
                }
                
                console.log('start process on: rtp://' + streamIp + ':' + streamPort);
                console.log('rtp rtpOffer:', sdpRtpOfferString);

                me.bindFFmpeg(streamIp, streamPort, sdpRtpOfferString );
            });
        })
    }  
    generateSdpStreamConfig(nodeStreamIp, port, audioport, callback) {
        if (typeof nodeStreamIp === 'undefined'
            || nodeStreamIp === null
            || typeof port === 'undefined'
            || port === null) {
            return callback('nodeStreamIp and port for generating Sdp Must be setted');
        }
        var sdpRtpOfferString = 'v=0\n';
        sdpRtpOfferString += 'o=- 0 0 IN IP4 ' + nodeStreamIp + '\n';
        sdpRtpOfferString += 's=KMS\n';
        sdpRtpOfferString += 'c=IN IP4 ' + nodeStreamIp + '\n';
        sdpRtpOfferString += 't=0 0\n';
        sdpRtpOfferString += 'm=audio ' + audioport + ' RTP/AVP 97\n';
        sdpRtpOfferString += 'a=recvonly\n';
        sdpRtpOfferString += 'a=rtpmap:97 PCMU/8000\n';
        sdpRtpOfferString += 'a=fmtp:97 profile-level-id=1;mode=AAC-hbr;sizelength=13;indexlength=3;indexdeltalength=3;config=1508\n';
        sdpRtpOfferString += 'm=video ' + port + ' RTP/AVP 96\n';
        sdpRtpOfferString += 'a=rtpmap:96 VP8/90000\n';
        sdpRtpOfferString += 'a=fmtp:96 packetization-mode=1\n';
        callback(null, sdpRtpOfferString);
    }    
    bindFFmpeg(streamip, streamport, sdpData ) {
        //var fn = '/sdp/'+streamip + '_' + streamport + '.sdp';
        var fn = __dirname +"/"+streamip + '_' + streamport + '.sdp';
        fs.writeFileSync(fn, sdpData);
        console.log( 'write sdp to file:', fn );
        var ffmpeg_args = [
            '-protocol_whitelist', 'file,udp,rtp',
            '-i', path.join('/sdp/', streamip + '_' + streamport + '.sdp'),
            '-vcodec', 'copy',
            '-acodec', 'copy',
            '-f', 'flv',
            'rtmp://127.0.0.1/live/' + streamip + '_' + streamport
        ].concat();
        var cmd = "ffmpeg "+ ffmpeg_args.join(' ');
        console.log(cmd); 
    };

}
channels = new TChannels();
channels.kms.config  = kmsConfig;
channels.load();